package com.cml.getway.core;

import com.cml.getway.common.util.PropertiesUtils;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.io.InputStream;
import java.util.Map;
import java.util.Properties;

/**
 * 姓名：陈茂林
 * 时间：2023/12/20
 * 描述：网关配置加载规则：优先级顺序如下：高的优先级会覆盖掉低的优先级
 *  * 		运行参数(最高) ->  jvm参数  -> 环境变量  -> 配置文件  -> 内部GetwayConfig对象的默认属性值(最低);
 */
@Slf4j
public class GetwayConfigLoader {
    private final static String CONFIG_FILE = "getway.properties";

    private final static String CONFIG_ENV_PREFIEX = "GETWAY_";

    private final static String CONFIG_JVM_PREFIEX = "getway.";

    private GetwayConfig getwayConfig = new GetwayConfig();
    private GetwayConfigLoader(){}

    public static GetwayConfigLoader getInstance(){
        return Singleton.INSTANCE;
    }

    public static GetwayConfig getGetwayConfig() {
        return getInstance().getwayConfig;
    }

    static class Singleton{
        private final static GetwayConfigLoader INSTANCE=new GetwayConfigLoader();
    }

    public GetwayConfig load(String[] args){
        loadConfigFile();
        loadSystemEnv();
        loadSystemProperties();
        loadStartArg(args);
        return getwayConfig;
    }

    private void loadStartArg(String[] args){
        if(args != null && args.length > 0) {
            Properties properties = new Properties();
            for(String arg : args) {
                if(arg.startsWith("--") && arg.contains("=")) {
                    properties.put(arg.substring(2, arg.indexOf("=")), arg.substring(arg.indexOf("=") + 1));
                }
            }
            PropertiesUtils.properties2Object(properties, getwayConfig);
        }
    }

    private void loadSystemProperties(){
        Properties properties = System.getProperties();
        PropertiesUtils.properties2Object(properties, getwayConfig, CONFIG_ENV_PREFIEX);
    }


    private void loadSystemEnv(){
        Map<String, String> env = System.getenv();
        Properties properties = new Properties();
        properties.putAll(env);
        PropertiesUtils.properties2Object(properties, getwayConfig, CONFIG_JVM_PREFIEX);
    }

    private void loadConfigFile(){
        InputStream is = GetwayConfigLoader.class.getClassLoader().getResourceAsStream(CONFIG_FILE);
        if(is != null){
            Properties properties = new Properties();
            try {
                properties.load(is);
                PropertiesUtils.properties2Object(properties, getwayConfig);
            } catch (IOException e) {
                //	warn
                log.warn("#GetwayConfigLoader# 加载配置文件: {} 错误" +
                        "", CONFIG_FILE, e);
            } finally {
                if(is != null) {
                    try {
                        is.close();
                    } catch (IOException e) {
                        //	ignore
                    }
                }
            }
        }

    }

}
